﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text;
using TestLargeModel.Application;

namespace TestLargeModel.Pages
{
    public class IndexModel : PageModel
    {
        //private readonly AIService _aiService;
        //private readonly HttpClient _httpClient;



        [BindProperty]
        public string InputText { get; set; }

        public string Response { get; set; }

        public void OnGet()
        {
            // 处理GET请求
        }

        //public async Task<IActionResult> OnPostAsync()
        //{
        //    //string apiKey = "1a57ee11-6361-4aae-a62f-8e819850e8dc";
        //    //string apiUrl = "https://api.volcengine.com/v1/chat/completions"; // 根据实际情况调整API URL


        //    string config = "{ \"Url\": \"https://ark.cn-beijing.volces.com/api/v3/chat/completions\", \"ApiKey\": \"1a57ee11-6361-4aae-a62f-8e819850e8dc\", \"EndpointId\": \"ep-20241223092549-xwdcc\" }";

        //    TyClient Client = new TyModel(config);

        //    if (!string.IsNullOrEmpty(InputText))
        //    {
        //        string result = Client.ChatAI(InputText);
        //        Response = result;
        //    }

        //    return Page(); // 返回到当前页面
        //}

        public async Task<IActionResult> OnPostAsync()
        {
            var inputText = Request.Form["inputText"];
            string config = "{ \"Url\": \"https://ark.cn-beijing.volces.com/api/v3/chat/completions\", \"ApiKey\": \"1a57ee11-6361-4aae-a62f-8e819850e8dc\", \"EndpointId\": \"ep-20241223092549-xwdcc\" }";
            if (!string.IsNullOrEmpty(inputText))
            {

                TyClient Client = new TyModel(config);
                // 调用流式返回的 AI 方法
                var responses = Client.StreamChatAI(inputText);

                var sb = new StringBuilder();

                // 逐步收集并显示响应
                await foreach (var responseChunk in responses)
                {
                    sb.Append(responseChunk);
                    // 这里您可以存储响应，以便在网页上逐步显示
                    Response = sb.ToString();
                    // 通过 `await Task.Delay()` 模拟实时更新
                    await Task.Delay(100); // 延迟以模拟流式响应
                }
            }
            return Page();
        }

        // 根据API响应定义Choice类
        public class Choice
        {
            public string Message { get; set; }
        }
    }
}